package com.giveme5.common.api.exception;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;

import org.nutz.mvc.adaptor.ParamInjector;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.impl.AdaptorErrorContext;

public class ApiAdaptorErrorContext extends AdaptorErrorContext {

	/**
	 * 报错的参数名
	 */
	private String[] paramNames;

	public ApiAdaptorErrorContext(int size) {
		super(size);
		paramNames = new String[size];
	}

	public Collection<String> getErrorMsgs() {
		Collection<String> result = new ArrayList<String>();
		for (String parame : paramNames) {
			if (parame != null) {
				result.add("参数" + parame + "数据类型错误!");
			}
		}
		return result;
	}

	@Override
	public void setError(int index, Throwable err, Method method, Object value, ParamInjector inj) {
		super.setError(index, err, method, value, inj);
		// 获取报错的参数名
		if (method != null) {
			Annotation[] annotations = method.getParameterAnnotations()[index];
			for (Annotation annotation : annotations) {
				if (annotation instanceof Param) {
					paramNames[index] = ((Param) annotation).value();
					break;
				}
			}
		}
	}

	public String getParamName(int index) {
		return paramNames[index];
	}

}
